package backstage.sys.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import backstage.menu.util.MenuComparator;
import backstage.menu.vo.SysMenuVo;

public class Tree {

	public static List<SysMenuVo> getResult(List<SysMenuVo> src) {
		List<SysMenuVo> parents = new ArrayList<SysMenuVo>();
		List<SysMenuVo> last = new ArrayList<SysMenuVo>();
		for (SysMenuVo ent : src) {
			if (ent.isCheckGroup()) {
				SysMenuVo result = ent;
				result.setChildren(new ArrayList<SysMenuVo>());
				parents.add(result);
			}else{
				last.add(ent);
			}
		}
		MenuComparator mc = new MenuComparator();
		Collections.sort(parents, mc);
		buildTree(parents, last, mc);
		return parents;

	}

	private static void buildTree(List<SysMenuVo> parents, List<SysMenuVo> others,MenuComparator mc) {
		for (Iterator<SysMenuVo> it = parents.iterator(); it.hasNext();) {
			SysMenuVo vi = it.next();
			if (vi.getId() != null) {
				for (Iterator<SysMenuVo> otherIt = others.iterator(); otherIt.hasNext();) {
					SysMenuVo inVi = otherIt.next();
					if (vi.getLabeling().equals(inVi.getOnlabeling())) {
						if (null == vi.getChildren()) {
							vi.setChildren(new ArrayList<SysMenuVo>());
						}
						vi.getChildren().add(inVi);
						otherIt.remove();
					}
				}
				Collections.sort(vi.getChildren(), mc);
			}
		}
	}
	
}
